import Config from './Config.js'
import Data from './Data.js'
import File from '../../utils/Filemage.js'
import networks from '../../utils/networks.js'
import downfile from '../../utils/downfile.js'
import { __dirname } from '../../components/Path.js'
import common from '../../utils/common.js'
import timer from '../../utils/Timer.js'
import { segment } from '../../component/icqq/index.js'
import { cm } from './CMLoad.js'
let stateArr = {}
let Common
try {
  Common = (await import('#miao')).Common
} catch {}
const SymbolTimeout = Symbol('Timeout')
const SymbolResolve = Symbol('Resolve')
/**
 * @param name 插件名称
 * @param dsc 插件描述
 * @param handler handler配置
 * @param handler.key handler支持的事件key
 * @param handler.fn handler的处理func
 * @param namespace namespace，设置handler时建议设置
 * @param event 执行事件，默认message
 * @param priority 优先级，数字越小优先级越高
 * @param rule
 * @param rule.reg 命令正则
 * @param rule.fnc 命令执行方法
 * @param rule.event 执行事件，默认message
 * @param rule.log  false时不显示执行日志
 * @param rule.permission 权限 master,owner,admin,all
 * @param task
 * @param task.name 定时任务名称
 * @param task.cron 定时任务cron表达式
 * @param task.fnc 定时任务方法名
 * @param task.log  false时不显示执行日志
 */
export default class Base {
  constructor (data) {
    this.name = data.name
    this.Data = new Data(data.name)
    this.Config = Config
    this.File = new File(__dirname)
    this.networks = networks
    this.downfile = downfile
    this.Path = __dirname
    this.cm = cm
    this.common = new common()
    this.event = data.event || 'message'
    this.priority = data.priority || 5000
    this.timer = timer
    this.segment = segment
    this.task = {
      /** 任务名 */
      name: data.task?.name || '',
      /** 任务方法名 */
      fnc: data.task?.fnc || '',
      /** 任务cron表达式 */
      cron: data.task?.cron || ''
    }

    /** 命令规则 */
    this.rule = data.rule || []
  }

  get Cfg () {
    return Config.GetCfg(this.name)
  }

  set Cfg (data) {
    Config.SetCfg(this.name, data.key, data.value)
  }

  reply (msg = '', quote = false, data = {}) {
    if (!this.e.reply || !msg) return false
    return this.e.reply(msg, quote, data)
  }

  conKey (isGroup = false) {
    return `${this.name}.${this.self_id || this.e.self_id}.${isGroup ? this.group_id || this.e.group_id : this.user_id || this.e.user_id}`
  }

  /**
   * @param type 执行方法
   * @param isGroup 是否群聊
   * @param time 操作时间
   * @param timeout 操作超时回复
   */
  setContext (type, isGroup, time = 120, timeout = '操作超时已取消') {
    const key = this.conKey(isGroup)
    if (!stateArr[key]) stateArr[key] = {}
    stateArr[key][type] = this.e
    if (time) {
      stateArr[key][type][SymbolTimeout] = setTimeout(() => {
        if (stateArr[key][type]) {
          const resolve = stateArr[key][type][SymbolResolve]
          delete stateArr[key][type]
          resolve ? resolve(false) : this.reply(timeout, true)
        }
      }, time * 1000)
    }
    return stateArr[key][type]
  }

  getContext (type, isGroup) {
    if (type) return stateArr[this.conKey(isGroup)]?.[type]
    return stateArr[this.conKey(isGroup)]
  }

  finish (type, isGroup) {
    const key = this.conKey(isGroup)
    if (stateArr[key]?.[type]) {
      clearTimeout(stateArr[key][type][SymbolTimeout])
      delete stateArr[key][type]
    }
  }

  awaitContext (...args) {
    return new Promise(
      (resolve) =>
        (this.setContext('resolveContext', ...args)[SymbolResolve] = resolve)
    )
  }

  resolveContext (context) {
    this.finish('resolveContext')
    context[SymbolResolve](this.e)
  }

  async makeGroupMsg (title, msg, isfk = false, user_id) {
    let nickname = Bot.nickname
    let uid = user_id || Bot.uin
    if (this.e.isGroup) {
      // let info = await Bot.getGroupMemberInfo(this.e.group_id, uid);
      let info = Bot.pickGroup(this.e.group_id, true).pickMember(uid).getInfo()
      nickname = info.card ?? info.nickname
    }
    let userInfo = {
      user_id: uid,
      nickname
    }
    let forwardMsg = []
    msg.forEach((item) => {
      let obj = {
        ...userInfo,
        message: item.content
      }
      if (item.time) {
        obj.time = item.time
      }
      forwardMsg.push(obj)
    })
    /** 制作转发内容 */
    if (this.e?.group?.makeForwardMsg) {
      forwardMsg = this.e.group.raw
        ? await this.e.group.raw.makeForwardMsg(forwardMsg)
        : await this.e.group.makeForwardMsg(forwardMsg)
    } else if (this.e?.friend?.makeForwardMsg) {
      forwardMsg = this.e.friend.raw
        ? await this.e.friend.raw.makeForwardMsg(forwardMsg)
        : await this.e.friend.makeForwardMsg(forwardMsg)
    } else {
      return msg.join('\n')
    }

    if (title) {
      /** 处理描述 */
      if (typeof forwardMsg.data === 'object') {
        let detail = forwardMsg.data?.meta?.detail
        if (detail) {
          detail.news = [{ text: title }]
        }
      } else {
        if (isfk) {
          forwardMsg.data = forwardMsg.data.replace(
            '<?xml version="1.0" encoding="utf-8"?>',
            '<?xml version="1.0" encoding="utf-8" ?>'
          )
        }
        forwardMsg.data = forwardMsg.data
          .replace(/\n/g, '')
          .replace(/<title color="#777777" size="26">(.+?)<\/title>/g, '___')
          .replace(/___+/, `<title color="#777777" size="26">${title}</title>`)
      }
    }

    return forwardMsg
  }

  async renderImg (plugin, tpl, data, cfg) {
    return Common.render(plugin, tpl, data, { ...cfg, e: this.e })
  }
}
